<template>
  <div>
    <!--
        导出 excel
        第一步: 安装
          npm i xlsx file-saver -S
          npm i script-loader -S
        第二步: 导入
          添加 util/excel.js 文件
        第三步: 使用
          参数说明:
            header: Array -> 导出数据的表头,默认值 []
            data: Array -> 导出的具体数据,默认值 []
            filename: String -> 导出文件名,默认值 excel-list
            autoWidth: Boolean -> 单元格是否要自适应宽度,默认值 true
            bookType: String -> 导出文件类型,默认值 xlsx
              可选值:xlsx csv txt 更多类型查看:https://github.com/SheetJS/sheetjs#supported-output-formats
          import('@/util/Export2Excel').then(excel => {
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename,
              autoWidth: this.autoWidth,
              bookType: this.type
            })
          })
     -->
    <el-select v-model="type">
      <el-option v-for="(item, index) in options" :key="item + index" :label="item" :value="item">
      </el-option>
    </el-select>
    <el-button type="primary" @click="handleDownload" :loading="downloadLoading">导出</el-button>
  </div>
</template>

<script>
export default {
  name: 'Xlsx',
  data () {
    return {
      type: 'xlsx',
      options: ['xlsx', 'csv', 'txt'],
      filename: 'test',
      autoWidth: true,
      downloadLoading: false,
      list: [{ id: 1, title: '哇哈哈哈哈', author: '陈亮', pageviews: '哈哈哈哈哈', display_time: '2020-07-03 15:17:23' }]
    }
  },
  methods: {
    handleDownload () {
      this.downloadLoading = true
      import('@/util/Export2Excel').then(excel => {
        // 导出 excel 的表头
        const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // 表头每列对应的字段属性名称
        const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.type
        })
        this.downloadLoading = false
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return this.parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    parseTime (time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string')) {
          if ((/^[0-9]+$/.test(time))) {
            // support "1548221490638"
            time = parseInt(time)
          } else {
            // support safari
            // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
            time = time.replace(new RegExp(/-/gm), '/')
          }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        return value.toString().padStart(2, '0')
      })
      return timeStr
    }
  }
}
</script>

<style>

</style>
